package com.jzo2o.health.handler;

import cn.hutool.core.collection.CollUtil;
import com.jzo2o.api.trade.RefundRecordApi;
import com.jzo2o.api.trade.dto.response.ExecutionResultResDTO;
import com.jzo2o.common.constants.UserType;
import com.jzo2o.health.model.OrdersCancelledDTO;
import com.jzo2o.health.model.domain.Orders;
import com.jzo2o.health.model.domain.OrdersCancelled;
import com.jzo2o.health.model.domain.OrdersRefund;
import com.jzo2o.health.model.dto.OrderCanelDTO;
import com.jzo2o.health.properties.OrdersJobProperties;
import com.jzo2o.health.service.IOrdersManagerService;
import com.jzo2o.health.service.IOrdersRefundService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 订单相关定时任务
 *
 * @author itcast
 * @create 2023/9/2 16:44
 **/
@Slf4j
@Component
public class OrdersHandler {

    @Resource
    private RefundRecordApi refundRecordApi;
    //解决同级方法调用，事务失效问题
    @Resource
    private OrdersHandler orderHandler;
    @Resource
    private OrdersJobProperties ordersJobProperties;
    @Resource
    private IOrdersManagerService ordersManagerService;

    @Resource
    private IOrdersRefundService ordersRefundService;

    /**
     * 支付超时取消订单
     * 每分钟执行一次
     */
    @XxlJob(value = "cancelOverTimePayOrder")
    public void cancelOverTimePayOrder() {
//1.查询出100个超时未支付的订单
        List<Orders> list = ordersManagerService.queryOverTimeNoPayOrdersByCount(100);
        if (CollUtil.isEmpty(list)) {
            return;
        }
        //2.挨个取消未支付且超时的订单（都是未支付状态的订单，
        // 需要修改orders表的order_status，新增order_canceled表记录）
        for (Orders orders : list) {
            OrderCanelDTO dto = new OrderCanelDTO();
            dto.setId(orders.getId());
            dto.setCancellerType(UserType.SYSTEM);
            dto.setCancelReason("超时未支付自动取消订单");
            ordersManagerService.cancelNoPayOrder(dto);
        }
    }

    /**
     * 订单退款异步任务
     */
    @XxlJob(value = "handleRefundOrders")
    public void handleRefundOrders() {
//1.先查询待退款记录
        List<OrdersRefund> ordersRefunds = ordersRefundService.queryRefundOrderListByCount(100);
        if (CollUtil.isEmpty(ordersRefunds)) {
            return;
        }
        //2.为这些退款记录的订单处理退款操作
        for (OrdersRefund ordersRefund : ordersRefunds) {
            Orders orders = ordersManagerService.getById(ordersRefund.getId());
            ordersManagerService.requestRefundOrder(ordersRefund.getId(),ordersRefund.getRealPayAmount(),orders.getTradingOrderNo());
        }
    }
}
